weighted_mean_ci <- function(data, var, weight, group_var) {
  var <- ensym(var)
  weight <- ensym(weight)
  group_var <- ensym(group_var)
  
  # Function to calculate weighted mean and confidence intervals for a subset
  calculate_stats <- function(subset_data) {
    var_values <- subset_data[[as_string(var)]]
    weights <- subset_data[[as_string(weight)]]
    
    weighted_mean <- sum(weights * var_values) / sum(weights)
    variance <- sum(weights * (var_values - weighted_mean)^2) / sum(weights)
    sd <- sqrt(variance)
    n <- nrow(subset_data)
    se <- sd / sqrt(n)
    ci_lower <- weighted_mean - qt(0.975, df = n - 1) * se
    ci_upper <- weighted_mean + qt(0.975, df = n - 1) * se
    
    data.frame(
      mean = weighted_mean,
      sd = sd,
      se = se,
      lb = ci_lower,
      ub = ci_upper
    )
  }
  
  # Apply the function to each group
  results <- data %>%
    group_by(!!group_var) %>%
    group_modify(~ calculate_stats(.x)) %>%
    ungroup()
  
  return(results)
}